import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000, // request timeout
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // config.headers['application'] = 1
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // if (response.config.headers.application == 3) {
    //   return response
    // }
    if (response.headers.filename) {
      // new Blob([data])用来创建URL的file对象或者blob对象
      const url = window.URL.createObjectURL(new Blob([response.data]))
      // 生成一个a标签
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      // 生成时间戳
      //  let timestamp=new Date().getTime();
      link.download = response.headers.filename
      document.body.appendChild(link)
      link.click()
      return
    } else if (response.config.responseType === 'blob' || response.config.responseType === 'arraybuffer') {
      // 下载excel类型
      // eslint-disable-next-line no-undef
      const blob = new Blob([response.data], { type: 'application/octet-stream;charset=ISO8859-1' }) // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
      // eslint-disable-next-line no-undef
      const downloadElement = document.createElement('a')
      // eslint-disable-next-line no-undef
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      console.log(response.headers['content-disposition'])

      // 获取文件名
      const str = response.headers['content-disposition'].split('=')[1]
      downloadElement.download = decodeURIComponent(str) // 下载后文件名
      // eslint-disable-next-line no-undef
      document.body.appendChild(downloadElement)
      downloadElement.click() // 点击下载
      // eslint-disable-next-line no-undef
      document.body.removeChild(downloadElement) // 下载完成移除元素
      // eslint-disable-next-line no-undef
      window.URL.revokeObjectURL(href) // 释放掉blob对象
      return response
    }
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if ([0, 1, -1].indexOf(res.result) === -1) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.result === 50008 || res.result === 50012 || res.result === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      } else if (res.result === 401) {
        MessageBox.confirm('你已被登出，请重新登录', '登录失效', {
          confirmButtonText: '重新登录',
          showCancelButton: false,
          type: 'warning'
        }).then(() => {
          store.dispatch('tagsView/delAllViews')
          store.dispatch('user/logout').then(() => {
            router.push('/login')
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
